<?php
/*
* @Author: 李明
* @Date: 2021-08-17 09:38:23
 * @LastEditTime: 2022-01-17 15:36:34
 * @LastEditors: 李明
* @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/bank/BankCardController.php
* @山东壹零贰肆信息科技有限公司
*/

namespace App\Http\Controllers\bank;

use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Http\Resources\BankCard as ResourcesBankCard;
use App\Http\Resources\Worker;
use App\Models\BankCard;
use App\Models\Image;
use App\Models\Order;
use App\Models\RolePower;
use App\Models\Worker as WorkerModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Utils;

class BankCardController extends Controller
{

    //银行卡的添加和修改
    public function BankCardSave(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
        try {
            $all = $request->all();
            $user_id = $all['user_id'];
            $bank_card_list = BankCard::where('user_id', $all['user_id'])->get();
            $is_default = isset($all['is_default']) ? $all['is_default'] : (count($bank_card_list) > 0 ? '2' : '1'); // 传了根据传的来，没传根据是否是第一张判断
            $account_name = $all['account_name'] ?? '';
            $bank_id = $all['bank_id'] ?? '';
            $bank_nums = $all['bank_num'] ?? '';
            if (env('COMPANY') == 3) {
                $bank_num = str_replace(' ', '', $bank_nums);
            } else {
                $bank_num = $bank_nums;
            }
            $bank_sum_name = $all['bank_sum_name'] ?? '';
            $image_ids = $all['image_ids'] ?? [];
        } catch (\Throwable $th) {
            return LMReturn::Error('传参出现错误', 'BCC001');
        }
        try {
            DB::beginTransaction(); //开启事务
            $bank_card = isset($all['id']) ? BankCard::find($all['id']) : new BankCard;

            $order_list = $bank_card->orders->whereIn("order_status", [4, 6]) ?? [];
            if (count($order_list) > 0 && ($account_name != $bank_card->account_name || $bank_id != $bank_card->bank_id || $bank_nums != $bank_card->bank_num || $bank_sum_name != $bank_card->bank_sum_name)) {
                return LMReturn::Error('抱歉您没权限修改，此银行卡已产生订单', 'BCC010');
            }
            $bank_card->account_name = $account_name;
            if ($bank_id != '') {
                $bank_card->bank_id = $bank_id;
            }
            if ($user_id != '') {
                $bank_card->user_id = $user_id;
            }
            $bank_card->bank_num = $bank_num;
            $bank_card->bank_sum_name = $bank_sum_name;
            $bank_card->is_default = $is_default;
            $bank_card->save();
            $bank_id = $bank_card->id;
            if ($is_default == '1') { // 如果是默认其他改成非默认
                $this->defaultChange($bank_id, $bank_card_list);
            }
            DB::commit(); //提交至数据库
        } catch (\Throwable $th) {
            DB::rollback(); //数据库回滚
            return LMReturn::Error('添加修改出现错误', 'BCC002');
        }
        // 如果返回false，则是修改时报错，数据库回滚，返回错误信息
        if (!Utils::UpImage($image_ids,  $bank_card->images, $bank_card->id, 1, $operation_id)) {
            return LMReturn::Error('添加修改图片出现错误其他信息已提交，请重新上传图片', 'BCC002');
        }
        return LMReturn::Success($bank_card);
    }

    /**
     * @description: 把传入之外的本人的银行卡改成非默认
     * @param {*} $bank_id  需要改成默认银行卡的  id
     * @param {*} $bankInfoList  当前所有银行卡列表
     * @return {*}
     */
    public function defaultChange($bank_id, $bankInfoList)
    { // bank_id改成默认的银行卡id，当前的银行卡列表
        foreach ($bankInfoList as $bank_card) {
            if ($bank_card->id != $bank_id) { // 如果id一样不做处理
                $bank_card->is_default = 2;
                $bank_card->save();
            }
        }
    }

    /**
     * @description: 删除银行卡
     * @param {Request} $request
     * @return {*}
     */
    public function BankCardDelete(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            //接收前端传递过来的值
            $all = $request->all();
            $bank_card_id = $all['id'];
        } catch (\Throwable $th) {
            return LMReturn::Error('请选择要删除的银行卡', 'BCC006');
        }
        try {
            $bank_card = BankCard::find($bank_card_id);
            $order_list = $bank_card->orders ?? [];
            if (count($order_list) > 0) {
                return LMReturn::Error('无法删除，此银行卡已产生订单', 'BCC007');
            } else {
                $bank_card->delete();
                return LMReturn::Success([], '删除成功');
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('删除失败', 'BCC008');
        }
    }

    //银行卡展示
    public function BankCardList(Request $request)
    {
        // 接收参数
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            //接收前端传递过来的值
            $all = $request->all();
        } catch (\Throwable $th) {
            return LMReturn::Error('传参错误', 'BCC003');
        }

        // 参数处理
        try {
            $where = [];
            if (isset($all['user_id'])) {
                $where[] = ["user_id", $all['user_id']];
            } else {
                return LMReturn::Error('请问您想查看哪位客户的银行卡？', 300); //  300缺少必传参数
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数发生错误', 'BCC004');
        }
        $bank_card = BankCard::where($where)
            ->with('images')
            ->orderBy("update_time", "desc")
            ->get();
        $bank_card_res = ResourcesBankCard::collection($bank_card);
        return LMReturn::Success($bank_card_res);
    }
}
